package org.nerve.util;

import javax.servlet.http.HttpServletRequest;

/**
 * @文件名称 :RequestUtil.java
 * @所在包 :com.nerve.human.common.util
 * @功能描述 :
 *	request 的工具类
 * @创建者 :集成显卡	1053214511@qq.com
 * 
 * @创建日期 :2013-4-9
 * @log :
 */
public class RequestUtil {
	
	/**
	 * 
	 *	@param req
	 *	@param name	参数名
	 *	@return
	 *  @date: 2013-4-9
	 */
	public static String getString(HttpServletRequest req, String name){
		return getString(req, name, null);
	}
	
	/**
	 * 
	 *	@param req
	 *	@param name	参数名
	 *	@param defaultValue	默认值
	 *	@return
	 *  @date: 2013-4-9
	 */
	public static String getString(HttpServletRequest req, String name, String defaultValue){
		String result = req.getParameter(name);
		if(result == null)
			result = defaultValue;
		return result;
	}
	
	/**
	 * 
	 *	@param req
	 *	@param name
	 *	@param defaultValue
	 *	@return
	 *  @date: 2013-4-9
	 */
	public static int getInt(HttpServletRequest req, String name, int defaultValue){
		String result = req.getParameter(name);
		try{
			return Integer.valueOf(result);
		}catch(Exception e){
			//e.printStackTrace();
			return defaultValue;
		}
	}
	
	/**
	 * 获取request的ip<br>
	 * 这个可以得到代理后的真正ip<br>
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
